<?php
namespace app\tripapi\controller;
use app\tripapi\model\TravelPlanItem;
use app\tripapi\model\TravelPlan;
use app\tripapi\model\TravelApply;
use app\tripapi\model\TravelApplyCustomer;
use think\Controller;
use think\Request;
use think\Db;
class Plan extends ApiBaseController
{
    private $TravelPlanItem;
    private $TravelPlan;
    private $TravelApply;
    private $TravelApplyCustomer;

    public function __construct()
    {
        parent::__construct();
        $this->departmentid = $_SESSION['LOGIN_DEPT_ID'];
        $this->uid = $_SESSION['LOGIN_UID']; // 填报人id
        $this->uname = str_replace(',', '', iconv('gbk', 'UTF-8', GetUserNameByUid($this->uid))); // 填报人姓名
        $this->TravelPlanItem = new TravelPlanItem();
        $this->TravelPlan = new TravelPlan();
        $this->TravelApply = new TravelApply();
        $this->TravelApplyCustomer = new TravelApplyCustomer();
    }

    /*
     * 首页列表页
     */
    public function index()
    {
        return $this->fetch();
    }

    /*
     * 出差申请单列表
     */
    public function GetListByAjax()
    {
        if($this->params['nid'] == 'null'){
            $nid = '';
        }else{
            $nid = $this->params['nid'];
        }
        $data['page'] = $this->params['page'];
        $data['limit'] = $this->params['limit'];
        $result = $this->TravelPlan->GetApplyList($this->uid, $data,$nid);
        foreach ($result as $key => $value) {
            $result[$key]['department'] = iconv('GBK', 'UTF-8', $value['department']);
            $result[$key]['user_name'] = iconv('GBK', 'UTF-8', $value['user_name']);
            $result[$key]['creator'] = iconv('GBK', 'UTF-8', $value['creator']);
            $result[$key]['to_user_step'] = iconv('GBK', 'UTF-8', $value['to_user_step']);
            $result[$key]['to_user_step1'] = iconv('GBK', 'UTF-8', $value['to_user_step1']);
            if($this->uid != $value['creator_id']){
                $result[$key]['isedit'] = 'false';
            }else{
                $result[$key]['isedit'] = 'true';
            }
            if($value['to_status_step'] == '0' && $value['to_status_step1'] == '0'){ // 员工提交 部门经理未审批 董事长无查阅权限
                $result[$key]['status1'] = "部门经理审批中";
            }
            if($value['to_status_step'] == '1' && $value['to_status_step1'] == '0'){ // 部门经理提交  董事长查阅
                $result[$key]['status1'] = "总监/总经理归档";
            }
            if($value['to_status_step'] == '1' && $value['to_status_step1'] == '1'){
                $result[$key]['status1'] = "审批完成";
            }
        }
        if(isset($result[0])){
            $count = $result['0']['count'];
        }else{
            $count = '0';
        }
        $json = array("status" => 200, "msg" => "获取成功", "count" => $count, "data" => $result);
        return json_api($json);
    }

    /*
     * 申请单添加
     */
    public function add()
    {
        $username = iconv('GBK','UTF-8',str_replace(',', '', GetUserNameByUid($this->uid)));
        $this->assign('username',$username);
        return $this->fetch();
    }

    /*
     * 申请单查看
     */
    public function show()
    {
        $uid = $this->uid;
        $id = $_GET['id'];
        $result = $this->TravelPlanItem->GetList($id);
        $approve = $this->TravelPlan->ShowButton($id, $uid);
        $this->assign('isshow', $approve);
        $this->assign('itemlist', $result);
        return $this->fetch();
    }

    /*
     * 总经办申请单查看
     */
    public function showitem()
    {
        $id = $_GET['id'];
        $result = $this->TravelApply->ManageGetItemById($id);
        $customer_item = $this->TravelApplyCustomer->GetCustomerItemById($id);
        $this->assign('traffic_self', isset($result['0']['traffic_self']) ? json_decode($result['0']['traffic_self']) : '');
        $this->assign('business_receive', isset($result['0']['business_receive']) ? json_decode($result['0']['business_receive']): '');
        $this->assign('budget_item', isset($result['0']['budget_item'])? json_decode($result['0']['budget_item']): '');
        $this->assign('customer_item', $customer_item);
        $this->assign('itemdetail', $result);
        return $this->fetch();
    }

    /*
     * 申请单编辑
     */
    public function edit()
    {
        $id = $_GET['id'];
        $travelplan = $this->TravelPlan->GetDetail($id);
        $this->assign('plandetail', $travelplan);
        $result = $this->TravelPlanItem->GetList($id);
        $this->assign('itemdetail', $result);
        return $this->fetch();
    }

    /*
     * 生成唯一单号方法
     */
    public function GetUniqueOrderId()
    {
        $prefix = "CC";
        $center = date('Ymd');
        $ymonth = date('Ym'); // 根据当前时间的年月 判定自增序列的条件 按年月度自增
        $lastid = $this->TravelPlan->field('plan_num')->order('id desc')->limit(1)->find();
        $last_plan_num = $lastid['plan_num'];
        if (strpos($last_plan_num, $ymonth) !== false) { // 根据当前时间的年月与数据库中最新一条记录的出差编号对比 若包含 则表示同月份 自增加1
            $number = substr($last_plan_num, 10, 4);
            $pre = substr($last_plan_num, 0, 10);
            if(strlen($number+1) == 3){
                $fix = str_pad($pre,11, 0, STR_PAD_RIGHT).($number + 1);
            }elseif(strlen($number+1) == 4){
                $fix = str_pad($pre,10, 0, STR_PAD_RIGHT).($number + 1);
            }elseif(strlen($number+1) == 2){
                $fix = str_pad($pre,12, 0, STR_PAD_RIGHT).($number + 1);
            }else{
                $fix = str_pad($pre,13, 0, STR_PAD_RIGHT).($number + 1);
            }
        } else { // 若不包含 则从1开始自增
            $fix = $prefix.$center.str_pad('',3, 0, STR_PAD_RIGHT) . '1'; // 向右侧添加000
        }
        return $fix;
    }

    /*
     * 保存
     */
    public function Save()
    {
        $this->params['user_id'] = $this->uid;
        $this->params['user_name'] = $this->uname;
        $this->params['department_id'] = $this->departmentid; // 填报部门id
        $this->params['plan_num'] = $this->GetUniqueOrderId(); // 月度出差计划单号
        $this->params['creator'] = $this->uname; // 创建人
        $this->params['creator_id'] = $this->uid; // 创建人id
        //存储 travel plan 总表
        $id = $this->TravelPlan->TravelPlanSave($this->params);
        if ($id['id']) { // 若总表存储成功 继续保存明细表
            $this->TravelPlanItem->TravelPlanItemSave($id['id'], $this->params);
            $retInfo = array("status" => 200, "msg" => "申请成功", "data" => $id);
        } else { // 总表保存失败 提示错误 不做明细表存储
            $retInfo = array("status" => 500, "msg" => '申请失败', "data" => array());
        }
        return json_api($retInfo);
    }

    /*
     *  更新
     */
    public function Update()
    {
        $this->params['user_id'] = $this->uid;
        $this->params['user_name'] = $this->uname;
        $this->params['department_id'] = $this->departmentid; // 填报部门id
        $this->params['creator'] = $this->uname; // 创建人
        $this->params['creator_id'] = $this->uid; // 创建人id
        $result = $this->TravelPlan->TravelPlanUpdate($this->params);
        if ($result) {
            $this->TravelPlanItem->TravelPlanItemUpdate($this->params);
            $retInfo = array("status" => 200, "msg" => "更新成功", "data" => array());
            return json_api($retInfo);
        } else {
            $retInfo = array("status" => 500, "msg" => "更新失败", "data" => array());
            return json_api($retInfo);
        }
    }

    /*
     * 删除
     */
    public function Delete()
    {
        $id = $_GET['id'];
        $result = $this->TravelPlan->PlanDelete($id);
        if ($result) {
            $this->TravelPlanItem->PlanItemDelete($id);
            $retInfo = array("status" => 200, "msg" => "删除成功", "data" => array());
            return json_api($retInfo);
        } else {
            $retInfo = array("status" => 500, "msg" => "删除失败", "data" => array());
            return json_api($retInfo);
        }
    }
    /*
     * 总经办权限 查看月度计划单所有列表页面
     */
    public function index_manager_plan()
    {
        return $this->fetch();
    }

    /*
     * 总经办权限 查看月度计划单所有列表页面
     */
    public function index_manager_planitem()
    {
        return $this->fetch();
    }

    /*
     * Ajax 总经办查看出差单列表
     */
    public function GetitemByAjax(){
        $data['page'] = $this->params['page'];
        $data['limit'] = $this->params['limit'];
        $result = $this->TravelApply->GetApplyItemList($data);
        if(isset($result[0])){
            $count = $result['0']['count'];
        }else{
            $count = '0';
        }
        $retInfo = array("status" => 200, "msg" => "获取成功", "data" => $result, 'count' => $count);
        return json_api($retInfo);
    }

    /*
     * 总经办权限 查看所有列表
     */
    public function GetAllListForManager(){
        $data['page'] = $this->params['page'];
        $data['limit'] = $this->params['limit'];
        $result = $this->TravelPlan->GetAllListForManager($data);
        foreach ($result as $key => $value) {
            $result[$key]['department'] = iconv('GBK', 'UTF-8', $value['department']);
            $result[$key]['user_name'] = iconv('GBK', 'UTF-8', $value['user_name']);
            $result[$key]['creator'] = iconv('GBK', 'UTF-8', $value['creator']);
            $result[$key]['to_user_step'] = iconv('GBK', 'UTF-8', $value['to_user_step']);
            $result[$key]['to_user_step1'] = iconv('GBK', 'UTF-8', $value['to_user_step1']);
            if($this->uid != $value['creator_id']){
                $result[$key]['isedit'] = 'false';
            }else{
                $result[$key]['isedit'] = 'true';
            }
            if($value['to_status_step'] == '0' && $value['to_status_step1'] == '0'){ // 员工提交 部门经理未审批 董事长无查阅权限
                $result[$key]['status1'] = "部门经理审批中";
            }
            if($value['to_status_step'] == '1' && $value['to_status_step1'] == '0'){ // 部门经理提交  董事长查阅
                $result[$key]['status1'] = "总监/总经理归档";
            }
            if($value['to_status_step'] == '1' && $value['to_status_step1'] == '1'){
                $result[$key]['status1'] = "审批完成";
            }
        }
        if(isset($result[0])){
            $count = $result['0']['count'];
        }else{
            $count = '0';
        }
        $json = array("status" => 200, "msg" => "获取成功", "count" => $count, "data" => $result);
        return json_api($json);
    }

    /*
     * 审批 / 驳回
     */
    public function TravelApprove(){
        $id = $_GET['id']; // 审批单id
        // 通过审批单id 查询 提交人
        $create_id = $this->TravelPlan->GetCreateUserById($id);
        // 根据创建人id 查询创建人所属部门
        $department_name = $this->TravelPlan->GetDepartmentBiUid($create_id);
        // 根据创建人所在的部门 查询 部门审批流选择项
        $approvelist = $this->TravelPlan->GetApproveList($id,$department_name, $this->uid);
//        print_r($approvelist);exit;
        $retInfo = array("status" => 200, "msg" => "审批成功", "data" => $approvelist);
        return json_api($retInfo);
    }
    /*
     * 筛选
     */
    public function SearchResult(){
        $data['page'] = $this->params['page'];
        $data['limit'] = $this->params['limit'];
        $data['department'] = $this->params['department'];
        $data['approve_people'] = $this->params['approve_people'];
        $data['travel_people'] = $this->params['travel_people'];
        $result = $this->TravelPlan->GetApplyListForSearch($this->uid, $data);
        foreach ($result as $key => $value) {
            $result[$key]['department'] = iconv('GBK', 'UTF-8', $value['department']);
            $result[$key]['user_name'] = iconv('GBK', 'UTF-8', $value['user_name']);
            $result[$key]['creator'] = iconv('GBK', 'UTF-8', $value['creator']);
            $result[$key]['to_user_step'] = iconv('GBK', 'UTF-8', $value['to_user_step']);
            $result[$key]['to_user_step1'] = iconv('GBK', 'UTF-8', $value['to_user_step1']);
            if($this->uid != $value['creator_id']){
                $result[$key]['isedit'] = 'false';
            }else{
                $result[$key]['isedit'] = 'true';
            }
            if($value['to_status_step'] == '0' && $value['to_status_step1'] == '0'){ // 员工提交 部门经理未审批 董事长无查阅权限
                $result[$key]['status1'] = "部门经理审批中";
            }
            if($value['to_status_step'] == '1' && $value['to_status_step1'] == '0'){ // 部门经理提交  董事长查阅
                $result[$key]['status1'] = "总监/总经理归档";
            }
            if($value['to_status_step'] == '1' && $value['to_status_step1'] == '1'){
                $result[$key]['status1'] = "审批完成";
            }
        }
        if(isset($result[0])){
            $count = $result['0']['count'];
        }else{
            $count = '0';
        }
        $json = array("status" => 200, "msg" => "获取成功", "count" => $count, "data" => $result);
        return json_api($json);
    }
}